var common = require('../../../util/common');
var aoi = require('../../../util/aoi');

module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
    this.channelService = this.app.get('channelService');
    this.sceneId = this.app.getCurServer().scene;
    this.channel = this.channelService.getChannel('scene_' + this.sceneId, true);
    this.cachedb = this.app.get('cachedb');
    this.aoi = new aoi(50, 50);
};

// 移动
Handler.prototype.move = function(msg, session, next) {
    var self = this;
    if (!session.uid) {
        common.invokeCallback(next, null, {code: 500, msg: '请先登录'});
        return;
    }
    self.cachedb.asyncGet(session.uid, function(err, data) {
        var player = JSON.parse(data);

        self.aoi.playerMove(session.uid, msg.x, msg.y, function(err, leaveList, updateList, enterList) {
            if (err) common.invokeCallback(next, new Error('player move failed!'));

            // 更新玩家在redis中的缓存信息，此处看看是否可以去掉redis中的缓存
            player.x = msg.x;
            player.y = msg.y;
            self.cachedb.asyncSet(session.uid, JSON.stringify(player));

            if (leaveList.length > 0) {
                var paramLeave = {
                    route: 'onLeave',
                    uid: player.uid,
                    sid: player.sid
                };
                self.channelService.pushMessageByUids(paramLeave, leaveList);
            }
            if (enterList.length > 0) {
                var paramEnter = {
                    route: 'onJoin',
                    uid: player.uid,
                    name: player.name,
                    sid: player.sid
                };
                self.channelService.pushMessageByUids(paramEnter, enterList);

                var memberlist = [];
                for (var index in enterList) {
                    var member = {
                        uid: enterList[index].uid,
                        sid: enterList[index].sid,
                        name: enterList[index].name
                    };
                    memberlist.push(member);
                }
                // 将区域新信息发送给玩家
                self.channelService.pushMessageByUids('onUserInfo', {members: memberlist}, [{
                    uid: player.uid,
                    sid: player.sid
                }]);
            }
            if (updateList.length > 0) {
                var paramUpdate = {
                    route: 'onMove',
                    uid: player.uid,
                    name: player.name,
                    sid: player.sid,
                    x: player.x,
                    y: player.y
                };

                // 发送玩家移动的信息
                self.channelService.pushMessageByUids(paramUpdate, updateList);
            }
            common.invokeCallback(next, null, {code: 200, msg: '移动成功'});
        });
    });
};

// 切换场景
Handler.prototype.changeScene = function(msg, session, next) {
    var self = this;
    if (!session.uid) {
        next(null, {code: 500, msg: '请先登录'});
        return;
    }

    // 离开场景channel
    self.channel.leave(session.uid, session.frontendId);
    self.aoi.playerLeave(session.uid, function(err, result) {
        if (err) {
            next(new Error('player leave failed!'));
        } else {
            self.cachedb.asyncGet(session.uid, function(err, data) {
                var player = JSON.parse(data);
                if (result.length > 0) {
                    var param = {
                        route: 'onLeave',
                        uid: player.uid,
                        sid: player.sid
                    };
                    self.channelService.pushMessageByUids(param, result);
                }
                var scene = session.get('scene') == 0 ? 1 : 0;
                player.scene = scene;
                self.app.rpc.scene.remoteHandler.join(scene, player, function(err) {
                    if (err) {
                        next(null, {code: 500, msg: '进入场景失败'});
                    } else {
                        self.cachedb.asyncSet(player.uid, JSON.stringify(player));
                        next(null, {code: 200, msg: '切换场景成功'});
                    }
                });
            });
        }
    });
};